package com.hrt.manage.users.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.hrt.base.BaseController;
import com.hrt.bean.UsersInfor;
import com.hrt.manage.users.service.UserInforService;
import com.hrt.util.MD5Tool;
import com.hrt.util.WebParams;

@Controller
@RequestMapping(value = "/manage/user")
public class UserInforController extends BaseController<UsersInfor> {

	@Autowired
	private UserInforService userInforService;

	public UserInforController() {

	}

	public UserInforService getUserInforService() {
		return userInforService;
	}

	public void setUserInforService(UserInforService userInforService) {
		this.userInforService = userInforService;
	}

	public List<UsersInfor> getList() {
		return list;
	}

	public void setList(List<UsersInfor> list) {
		this.list = list;
	}

	/**
	 * 
	 * @param pageIndex
	 * 
	 * @param pageSize
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/queryByPage")
	@ResponseBody
	public Map queryByPage(
			@RequestParam(value = "pageIndex", required = false) Integer pageIndex,
			@RequestParam(value = "pageSize", required = false) Integer pageSize,
			HttpServletRequest request) {
		Map resultMap = new HashMap();

		if (pageSize == null || "".equals(pageSize)) {
			pageSize = 30;
		}
		if (pageIndex == null || "".equals(pageIndex)) {
			pageIndex = 1;
		}
		setPageIndex(pageIndex);

		setPageSize(pageSize);

		setTotalCount(userInforService.totalCount());

		List<UsersInfor> resultList = userInforService.queryByPage(
				getPageIndex(), getPageSize());
		setList(resultList);

		this.setPageCount(this.computePageCount(this.getTotalCount(),
				this.getPageSize()));

		page = this.getPage();

		resultMap.put("pageResult", page);
		return resultMap;
	}

	/**
	 * 
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/list")
	public ModelAndView list(HttpServletRequest request) {
		ModelAndView view = new ModelAndView();

		list = userInforService.queryByPage(getPageIndex(), getPageSize());
		setTotalCount(userInforService.totalCount());
		this.setPageCount(this.computePageCount(this.getTotalCount(),
				this.getPageSize()));

		page = this.getPage();

		view.addObject("pageResult", page);
		// request.getSession().setAttribute("pageResult", page);
		return view;

	}

	@RequestMapping(value = "/delete", method = RequestMethod.POST)
	public @ResponseBody Long[] delete(
			@RequestParam(value = "ids", required = true) String ids,
			HttpServletResponse response) throws IOException {
		Long[] idArr = null;
		ModelAndView view = new ModelAndView();

		if (ids != null) {
			if (ids.indexOf(",") != -1) {
				String[] idStrs = ids.split(",");
				idArr = new Long[idStrs.length];
				for (int idx = 0; idx < idStrs.length; idx++) {
					idArr[idx] = Long.parseLong(idStrs[idx]);
				}
			} else {
				idArr = new Long[] { Long.parseLong(ids) };
			}

		}
		try {
			userInforService.deleteById(idArr);

			return idArr;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}

	}

	@RequestMapping(value = "/save", method = RequestMethod.POST)
	public void save(@ModelAttribute("userInfor") UsersInfor user,
			HttpServletRequest request, HttpServletResponse response) {
		ModelAndView model = new ModelAndView();
		System.out.println("save");
		
		try {
			if ("".equals(user.getLoginName()) || user.getLoginName() == null
					|| user.getPassword() == null
					|| "".equals(user.getPassword())) {

				throw new Exception("登陆名或密码未空");
			}
			user.setPassword(MD5Tool.MD5(user.getPassword()));
			userInforService.saveUser(user);

			response.sendRedirect("list.do");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@RequestMapping(value = "/show")
	@ResponseBody
	public Map show(@RequestParam(value = "id", required = true) String userId,
			HttpServletRequest request, HttpServletResponse response) {

		Map map = new HashMap();
		if (userId != null && !"".equals(userId)) {
			// Map resultMap=new HashMap<K, V>();
			System.out.println("showshowshowshowshow " + userId);
			UsersInfor user = this.userInforService
					.getUserByid(new Long(userId));
			if (user != null) {
				map = transBean2Map(user);
			}

		}
		return map;

	}
	
	@RequestMapping(value = "/lockUser")
	@ResponseBody
	public String lockUser(@RequestParam(value = "id", required = true) String userId,
			HttpServletRequest request, HttpServletResponse response) {

		
		if (userId != null && !"".equals(userId)) {
			// Map resultMap=new HashMap<K, V>();
			System.out.println("showshowshowshowshow " + userId);
			UsersInfor user = this.userInforService
					.getUserByid(new Long(userId));
			if (user != null) {
				user.setStatus(new Integer(1));
				this.userInforService.updateUser(user);
				return "success";
			}
			

		}
		return "fail";

	}
	
	@RequestMapping(value = "/unlockUser")
	@ResponseBody
	public String unlockUser(@RequestParam(value = "id", required = true) String userId,
			HttpServletRequest request, HttpServletResponse response) {

		
		if (userId != null && !"".equals(userId)) {
			// Map resultMap=new HashMap<K, V>();
			System.out.println("showshowshowshowshow " + userId);
			UsersInfor user = this.userInforService
					.getUserByid(new Long(userId));
			if (user != null) {
				user.setStatus(new Integer(0));
				this.userInforService.updateUser(user);
				return "success";
			}
			

		}
		return "fail";

	}
	
	

	@RequestMapping(value = "/update", method = RequestMethod.POST)
	public void update(@ModelAttribute("userInfor") UsersInfor user,
			HttpServletRequest request, HttpServletResponse response) {
		System.out.println("update");
		System.out.println(user.getLoginName());
		System.out.println(user.getPassword());
		System.out.println(user.getNote());

		try {
			if ("".equals(user.getLoginName()) || user.getLoginName() == null
					|| user.getPassword() == null
					|| "".equals(user.getPassword())) {

				throw new Exception("登陆名或密码未空");
			}
			user.setPassword(MD5Tool.MD5(user.getPassword()));
			userInforService.updateUser(user);

			response.sendRedirect("list.do");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 
	 */
	@RequestMapping(value = "/welcome")
	public void welcome(HttpServletResponse response) {
             try {
				response.sendRedirect("/manage/login.jsp");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	}

	/**
	 * 后台用户登录
	 * 
	 * @param username
	 * @param password
	 */
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public ModelAndView login(@ModelAttribute("loginfrm") UsersInfor user,HttpServletRequest request,HttpServletResponse response) {
		ModelAndView view = new ModelAndView();
		try {
			if ("".equals(user.getLoginName()) || user.getLoginName() == null
					|| user.getPassword() == null
					|| "".equals(user.getPassword())) {

				throw new Exception("登陆名或密码未空");
			}
			user.setPassword(MD5Tool.MD5(user.getPassword()));

			user=userInforService.login(user.getLoginName(), user.getPassword());
			if(user!=null && user.getId()!=null)
			{
				view.setViewName("/manage/main");
				setOnlineManager(user,request,response);
			
				
			}else{
				view.setViewName("/manage/err_msg");
				view.addObject("error_msg", "登陆失败");
			}

			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			view.setViewName("/manage/err_msg");
			view.addObject("error_msg", "登陆失败");
			e.printStackTrace();
			
		}
		return view;
	}
	
	@RequestMapping(value = "/logout")
	public ModelAndView logout(HttpServletRequest request,HttpServletResponse response) {
		ModelAndView view = new ModelAndView();
		UsersInfor user=getOnlineManager(request, response);
		
		if(user!=null){
			request.getSession().removeAttribute(WebParams.ON_LINE_MANAGER);
		}
		try {
			response.sendRedirect("/login.jsp");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return view;
	}

	

}
